<template>
  <div class="container">
    <div class="app-container">
      <!-- 角色管理的内容 -->
      <div class="role-opreate">
        <el-button type="primary" size="mini" @click="showDialog = true">
          添加角色
        </el-button>
      </div>
      <!-- 放置table组件 -->
      <el-table :data="list">
        <!-- 放置列 -->
        <el-table-column prop="name" align="center" width="200px" label="角色">
          <template v-slot=" { row } ">
            <el-input v-if="row.isEdit" v-model="row.editRow.name" size="mini" />
            <span v-else>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="state" align="center" width="200px" label="启用">
          <!-- 自定义结构 -->
          <template v-slot="{ row }">
            <el-switch v-if="row.isEdit" v-model="row.editRow.state" :active-value="1" :inactive-value="0" />
            <span v-else> {{ row.state ===1 ? "已启用" : row.state === 0 ? "未启用" : "无" }} </span>
          </template>
        </el-table-column>
        <el-table-column prop="description" align="center" label="描述">
          <template v-slot="{ row }">
            <el-input v-if="row.isEdit" v-model="row.editRow.description" type="textarea" />
            <span v-else>{{ row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template v-slot=" { row }">
            <!-- 编辑装填 -->
            <template v-if="row.isEdit">
              <el-button type="primary" size="mini" @click="btnEditOK(row)">确定</el-button>
              <el-button size="mini" @click="row.isEdit = false">取消</el-button>
            </template>
            <!-- 默认状态 -->
            <template v-else>
              <el-button size="mini" type="text" @click="btnPression(row.id)">分配权限</el-button>
              <el-button size="mini" type="text" @click="btnEditRow(row)">编辑</el-button>
              <el-popconfirm
                title="这是一段内容确定删除吗？"
                @onConfirm="confirmDel(row.id)"
              >
                <el-button slot="reference" style="margin-left: 10px" size="mini" type="text">删除</el-button>
              </el-popconfirm>
            </template>
          </template>

        </el-table-column>
      </el-table>
      <!-- 放置分页组件 -->
      <el-row type="flex" style="height: 60px;" align="middle" justify="end">
        <el-pagination
          :page-size="pagePararms.pagesize"
          :page-count="pagePararms.page"
          :total="pagePararms.total"
          layout="prev, pager, next"
          @current-change="changePage"
        />
      </el-row>
    </div>
    <!-- 添加弹层 -->
    <el-dialog
      width="500px"
      :visible.sync="showDialog"
      title="添加角色"
      @close="btnCancel"
    >
      <!-- 弹层内容 -->
      <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="120px">
        <el-form-item prop="name" label="角色名称">
          <el-input v-model="roleForm.name" style="width: 300px;" size="mini" />
        </el-form-item>
        <!--  -->
        <el-form-item label="启用" prop="state">
          <el-switch v-model="roleForm.state" :active-value="1" :inactive-value="0" size="mini" />
        </el-form-item>
        <el-form-item prop="description" label="角色描述">
          <el-input v-model="roleForm.description" type="textarea" :rows="3" style="width: 300px;" size="mini" />
        </el-form-item>
        <el-form-item>
          <el-row type="flex" justify="center">
            <el-col :span="12">
              <el-button type="primary" size="mini" @click="btnOK">确定</el-button>
              <el-button size="mini" @click="btnCancel">取消</el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 分配角色弹层 -->
    <el-dialog
      :visible.sync="showPressionDialog"
      title="分配权限"
    >
      <el-tree
        ref="permTree"
        node-key="id"
        check-strictly
        :data="premissionData"
        :props="{label:'name'}"
        :default-checked-keys="permIds"
        show-checkbox
        default-expand-all
      />
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="6">
          <el-button type="primary" size="mini" @click="btnPressionOK">确定</el-button>
          <el-button size="mini" @click="showPressionDialog = false">取消</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>
<script>
import { getRoleList, addRole, updateRole, delRow, getRoleDetails, assignPrem } from '@/api/role'
import { getPremissionList } from '@/api/permission'
import { transListToTreeData } from '@/utils'
export default {
  name: 'Role',
  data() {
    return {
      list: [],
      roleForm: {
        name: '',
        state: 0,
        description: ''
      },
      rules: {
        name: [{
          required: true,
          message: '角色名称不能为空',
          trigger: 'blur'
        }],
        description: [
          {
            required: true,
            message: '角色描述不能为空',
            trigger: 'blur'
          }
        ]

      },
      showDialog: false, // 控制弹层
      pagePararms: {
        // 当前页
        page: 1,
        // 每页多少条
        pagesize: 5,
        // 总页数
        total: 0
      },
      showPressionDialog: false,
      premissionData: [],
      currentRoleId: null,
      permIds: []
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    async getRoleList() {
      const { rows, total } = await getRoleList(this.pagePararms)
      this.list = rows // 赋值数据
      this.pagePararms.total = total
      // 添加行标记
      this.list.forEach(item => {
        // 添加一个属性，初始值位false item.isEdit = false
        this.$set(item, 'isEdit', false)
        this.$set(item, 'editRow',
          {
            name: item.name,
            state: item.state,
            description: item.description
          })
      })
    },
    // 切换分页时请求新的数据
    changePage(newPage) {
      // alert(newPage)
      this.pagePararms.page = newPage
      this.getRoleList()
    },
    // 添加角色的方法
    btnOK() {
      this.$refs.roleForm.validate(async isOK => {
        if (isOK) {
          console.log('111')
          await addRole(this.roleForm)
          this.$message.success('新增角色成功')
          this.getRoleList()
          this.btnCancel()
        }
      })
    },
    // 取消按钮方法
    btnCancel() {
      this.$refs.roleForm.resetFields() // 重置表单
      this.showDialog = false // 关闭弹出层
    },
    // 编辑按钮方法
    btnEditRow(row) {
      row.isEdit = true
      row.editRow.name = row.name
      row.editRow.state = row.state
      row.editRow.description = row.description
    },
    // 编辑确定按钮的方法
    async btnEditOK(row) {
      if (row.editRow.name && row.editRow.description) {
        // 下一步操作
        await updateRole({ ...row.editRow, id: row.id })
        this.$message.success('更新角色成功')
        Object.assign(row, { ...row.editRow, isEdit: false })
      } else {
        this.$message.warning('角色和描述不能为空')
      }
    },
    // 删除按钮
    async confirmDel(id) {
      await delRow(id)
      this.$message.success('删除角色成功')
      if (this.list.length === 1) this.pagePararms.page--
      this.getRoleList()
    },
    async btnPression(id) {
      this.currentRoleId = id
      const { permIds } = await getRoleDetails(id)
      this.permIds = permIds
      this.premissionData = transListToTreeData(await getPremissionList(), 0)
      console.log(this.premissionData)
      this.showPressionDialog = true
    },
    // 分配权限点击确定时触发
    async btnPressionOK() {
      await assignPrem({
        id: this.currentRoleId,
        permIds: this.$refs.permTree.getCheckedKeys()
      })
      this.$message.success('权限分配成功')
      this.showPressionDialog = false
    }
  }
}
</script>
<style scoped>
.role-opreate{
  padding: 10px;
}
</style>
